package com.gpipe.tools;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.List;
import java.util.Map.Entry;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.gpipe.dbwriter.Mysql;
import com.gpipe.dirwatcherRealtime.Conf;
import com.gpipe.dirwatcherRealtime.DirectorySnapshotRealtime;
import com.gpipe.dirwatcherRealtime.InitialMethod;

public class Tools {
    /**
     * @param listSumRecords(lac|ci|nbr|starttime:endtime|duration -- second period)
     * @return listSumRecords(lac|ci|nbr|starttime:endtime|duration -- second period)
     * @function group by nbr order by starttime sum(the same lac|ci 's duration)
     */
    public Map<? extends String, ? extends String> getListSumRecords(Map<String, String> listSumRecords) {
        Map<String, String> result = new HashMap<String, String>();
        return result;
    }

    /**
     * 从基站配置表中读取所有的基站信息和给出的经纬度信息进行比对找出距离最近的几个基站
     *
     * @param num        输出最近的几条记录
     * @param longtitude 指定查找的经度
     * @param latitude   指定查找的纬度
     */
    public void getNearbyBase(int num, String longtitude, String latitude) {

        InitialMethod initialMethod = new InitialMethod();
        Map<String, BaseAreaModel> baseMap = initialMethod.getBaseArea();
        Iterator iterBaseMap = baseMap.entrySet().iterator();
        List<ToolModelGetDistance> sortList = new ArrayList<>();

        while (iterBaseMap.hasNext()) {
            Map.Entry<String, BaseAreaModel> entry = (Map.Entry) iterBaseMap.next();
            String key = entry.getKey();
            BaseAreaModel val = entry.getValue();
            ToolModelGetDistance model = new ToolModelGetDistance(val, longtitude, latitude);
            if(model.getDistance()==-1){
                continue;
            }
            sortList.add(model);
        }

        Collections.sort(sortList, new Comparator<ToolModelGetDistance>() {
            @Override
            public int compare(ToolModelGetDistance o1, ToolModelGetDistance o2) {
                return o1.getDistance().compareTo(o2.getDistance());
            }
        });

        System.out.println(sortList.get(0).getLac()+"|"+sortList.get(0).getCi());


    }


    //从本地获取listSum的数据
    public void getListSum(String filePath) {
        Tools tools = new Tools();
        BufferedReader readerLoc = tools.readLocFile(filePath);
        String lineLoc = null;
        try {
            if (readerLoc != null) {
                while ((lineLoc = readerLoc.readLine()) != null) {
                    String[] cols = lineLoc.split("\\|", -1);
                    SignalList sl = new SignalList(cols[5], cols[6], cols[3], cols[7], cols[8], cols[2]);
                    List<SignalList> val = DirectorySnapshotRealtime.listSumIncreRecords.get(cols[3]);
                    if (val == null) {
                        val = new ArrayList<SignalList>();
                    }
                    val.add(sl);
                    DirectorySnapshotRealtime.listSumIncreRecords.put(cols[3], val);
                }
                readerLoc.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 用来手工从睿总数据库读出数据导入到亿迅数据库
     *
     * @param tableName 迁移的表名
     * @param filterCol 条件字段
     * @param filterVal 条件值
     */
    public void moveData(String tableName, String filterCol, String filterVal) {
        Mysql mysql = new Mysql();

        //本地数据库
//        String dbtns = "jdbc:mysql://localhost:3306/signaldb?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8";
//        String user = "root";
//        String pass = "123567";
//        String dbclass = "com.mysql.jdbc.Driver";//"org.gjt.mm.mysql.Driver";

        //睿总数据库
        String dbtns = "jdbc:mysql://121.8.228.24:3306/signaldb?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8";
        String user = "signal";
        String pass = "sig123!@#NAL";
        String dbclass = "com.mysql.jdbc.Driver";//"org.gjt.mm.mysql.Driver";
        String sql = "";
        if (GpipeInit.isNotEmpty(filterCol) && GpipeInit.isNotEmpty(filterVal)) {
            sql = "select * from " + tableName + " where " + filterCol + "='" + filterVal + "'";
        } else {
            sql = "select * from " + tableName;
        }


        Connection conn = mysql.commanCreateConnect(dbtns, dbclass, user, pass);
        System.out.println("开始读取数据");
        ResultSet resultSet = mysql.readMysql(sql, conn);
        System.out.println("读完数据");
        String sqlDesc = "desc " + tableName;

        ResultSet resultSetDesc = mysql.readMysql(sqlDesc, conn);
        List<String[]> in = new ArrayList<>();

        String str1 = new String();
        String str2 = new String();
        int i = 0;

        try {
            while (resultSetDesc.next()) {
                i++;
                str1 = str1.concat(resultSetDesc.getString(1)).concat(",");
                str2 = str2.concat("?,");

            }

            while (resultSet.next()) {
                String[] s = new String[i];
                for (int j = 1; j <= i; j++) {
//                    System.out.println(resultSet.getString(j));

                    s[j - 1] = resultSet.getString(j);

                }
                in.add(s);

            }

            resultSet.close();

            conn.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }

        //本地数据库
//        String dbtns1 = "jdbc:mysql://localhost:3306/signaldb?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8";
//        String user1 = "root";
//        String pass1 = "123567";
//        String dbclass1 = "com.mysql.jdbc.Driver";//"org.gjt.mm.mysql.Driver";

        //亿迅数据库
        String dbtns1 = "jdbc:mysql://132.122.1.201:3306/jtj?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8";
        String user1 = "czp";
        String pass1 = "123456";
        String dbclass1 = "com.mysql.jdbc.Driver";//"org.gjt.mm.mysql.Driver";

        String sql1 = "INSERT INTO " + tableName + " (" + str1.substring(0, str1.length() - 1) + ") VALUES (" + str2.substring(0, str2.length() - 1) + ")";
        System.out.println(sql1 + "--" + i);

        Connection conn1 = mysql.commanCreateConnect(dbtns1, dbclass1, user1, pass1);

        mysql.writeMysql(in, sql1, conn1);

        try {
            conn1.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        in.clear();


    }


    //用来手工从睿总数据库读出数据导入到我电脑本地的目录
    public void moveDataToLocal(String tableName, String filterCol, String filterVal) throws IOException {
        Mysql mysql = new Mysql();

        //睿总数据库
        String dbtns = "jdbc:mysql://121.8.228.24:3306/signaldb?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8";
        String dbclass = "com.mysql.jdbc.Driver";//"org.gjt.mm.mysql.Driver";
        String user = "signal";
        String pass = "sig123!@#NAL";
        String sql = "";
        if (GpipeInit.isNotEmpty(filterCol) && GpipeInit.isNotEmpty(filterVal)) {
            sql = "select * from " + tableName + " where " + filterCol + "='" + filterVal + "'";
        } else {
            sql = "select * from " + tableName;
        }


        Connection conn = mysql.commanCreateConnect(dbtns, dbclass, user, pass);
        System.out.println("开始读取数据");
        ResultSet resultSet = mysql.readMysql(sql, conn);
        System.out.println("读完数据");
        String sqlDesc = "desc " + tableName;

        ResultSet resultSetDesc = mysql.readMysql(sqlDesc, conn);
        List<String[]> in = new ArrayList<>();

        String str1 = new String();
        String str2 = new String();
        int i = 0;


        //本地目录配置
        String localPath = "E:\\testLog\\data\\";
        String filePath = localPath + File.separator + tableName + File.separator + tableName + "_" + filterVal + ".txt";

        System.out.println("本地文件目录：" + filePath);
        File file = new File(filePath);

        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);

        try {
            while (resultSetDesc.next()) {
                i++;
                str1 = str1.concat(resultSetDesc.getString(1)).concat(",");
                str2 = str2.concat("?,");

            }

            while (resultSet.next()) {
                String[] s = new String[i];
                String str = new String();
                for (int j = 1; j <= i; j++) {
//                    System.out.println(resultSet.getString(1));

                    s[j - 1] = resultSet.getString(j);
                    str = str + "|" + resultSet.getString(j);

                }
                in.add(s);
                bw.write(str + "\n");

            }

            conn.close();
            bw.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }


    }


    // tool
    public String getJSONelement(String fileStr, String key) throws IOException {
        JsonParser parser = new JsonParser(); // 创建JSON解析器
        JsonObject object = (JsonObject) parser.parse(fileStr);
        Iterator iterator = object.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, JsonElement> entry = (Entry<String, JsonElement>) iterator.next();
            if (entry.getKey().equals(key)) {
                return entry.getValue().toString();
            }
        }
        return null;
    }

    // tool
    public JsonArray getJsonArray(String fileStr) {
        JsonParser parser = new JsonParser(); // 创建JSON解析器
        JsonArray array = (JsonArray) parser.parse(fileStr);
        return array;
    }

    // tool
    public String getFilePath(String path, String fileName) {
        String result = "";
        if (path.endsWith(File.separator)) {
            result = path.concat(fileName);
        } else {
            result = path.concat(File.separator).concat(fileName);
        }

        return result;
    }

    public List parseStrToList(String str) {
        List<Point> lists = new ArrayList<Point>();

        JsonArray midArray = arrayPrase(str);
//		System.out.println("midArray[0]="+midArray.get(0));
//		System.out.println("midArray[1]="+midArray.get(1));
//		System.out.println("midArray.size="+midArray.size());

        if (midArray.get(0).toString().contains("[[")) {
//			System.out.println("需要下鉆");
            List<List> listsMult = new ArrayList<List>();
            for (JsonElement je : midArray) {
                JsonArray midArray2 = arrayPrase(je.toString());
                for (JsonElement je1 : midArray2) {
                    Point p = new Point();
                    p.setPoint(je1.toString());
                    lists.add(p);
                }
                listsMult.add(lists);
            }

            return listsMult;

        } else {
            //到了最底層了[113.233,23.0802]
//			System.out.println("到了最底層");
            for (JsonElement je : midArray) {
                Point p = new Point();
                p.setPoint(je.toString());
                lists.add(p);

            }

            return lists;

//			for(Point pp :lists) {
//				System.out.println(pp.print());
//			}
        }


    }

    private JsonArray arrayPrase(String str) {
        JsonArray array = new JsonArray();

        do {
            array = getJsonArray(str);
//			array.
            if (array.size() <= 0) {
                return array;
            }
            str = array.get(0).toString();

        } while (array.size() <= 1);

        return array;

    }

    public String getPath() {
        String jarPath = getJarPath();
        return jarPath.substring(0, jarPath.lastIndexOf(File.separator));
    }

    public BufferedReader readLocFile(String filePath) {
        String ST = GpipeInit.writeLogs("--info--:开始读文件" + filePath);

        BufferedReader reader = null;
        try {
            reader = GpipeInit.unZipOutReader(filePath);
        } catch (FileNotFoundException e) {
            return reader;
        }


        String ET = GpipeInit.writeLogs("--info--:文件已读完" + filePath);
        GpipeInit.writeLogs("--info--:读文件" + filePath + "总时长:" + GpipeInit.duration(ST, ET));
        return reader;
    }

    //先擦出数据，然后写
    public void writeLocFile(String filePath, String content) {
        String ST = GpipeInit.writeLogs("--info--:开始写文件" + filePath);
        FileWriter fw = null;
        try {
            fw = new FileWriter(filePath);
            fw.write(content);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String ET = GpipeInit.writeLogs("--info--:文件已写完" + filePath);
        GpipeInit.writeLogs("--info--:写文件" + filePath + "总时长:" + GpipeInit.duration(ST, ET));
    }

    public void deleteFile(String path, String date) {
        File dir = new File(path);
        if (dir.isDirectory()) {
            File flist[] = dir.listFiles();
            for (File f : flist) {
                if (f.isFile() && f.getName().contains(date)) {
                    f.delete();
                }
            }
        } else {
            GpipeInit.writeLogs("--info--:" + dir + "不是一个目录");
        }
    }

    public boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                GpipeInit.writeLogs("--info--:删除单个文件" + fileName + "成功！");
                return true;
            } else {
                GpipeInit.writeLogs("--info--:删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            GpipeInit.writeLogs("--info--:删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }


    public String getJarPath() {
        URL url = Tools.class.getProtectionDomain().getCodeSource().getLocation();
        String filePath = null;
        try {
            filePath = URLDecoder.decode(url.getPath(), "utf-8");// 转化为utf-8编码
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (filePath.endsWith(".jar")) {// 可执行jar包运行的结果里包含".jar"
            // 截取路径中的jar包名
            filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
        }

        File file = new File(filePath);

        // /If this abstract pathname is already absolute, then the pathname
        // string is simply returned as if by the getPath method. If this
        // abstract pathname is the empty abstract pathname then the pathname
        // string of the current user directory, which is named by the system
        // property user.dir, is returned.
        filePath = file.getAbsolutePath();//得到windows下的正确路径
        return filePath;
    }


    public static void main(String[] args) throws IOException {

        Tools tools = new Tools();


        String[] date = new String[]{"2017-08-20","2017-08-21","2017-08-22"};
        for(String str:date){
            tools.moveData("od_summ_2period_amount_b_area","date",str);
            tools.moveData("od_summ_2period_amount_m_area","date",str);
            tools.moveData("od_summ_2period_distance_b_area","date",str);
            tools.moveData("od_summ_2period_distance_m_area","date",str);
            tools.moveData("od_summ_2period_od_b_area","date",str);
            tools.moveData("od_summ_2period_od_m_area","date",str);
            tools.moveData("od_summ_2period_od_s_area","date",str);
        }

//        System.out.println(tools.getPath());
//        tools.writeLocFile(tools.getPath()+File.separator+"midData"+File.separator+"list.txt","test\ntedddst");

//        BufferedReader reader= tools.readLocFile(tools.getPath()+File.separator+"midData"+File.separator+"list.txt");
//        String line =null;
//        try {
//            if(reader!=null) {
//                while ((line = reader.readLine()) != null) {
//                    System.out.println(line);
//                }
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
}
